using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Security.DataLayer;
using Security.Domain;
using Security.Helpers;
using Security.Specs.Common;
using Security.Specs.DataLayer;
using Security.Specs.Services;
using Security.Specs.Implementation.Common;

namespace Security.Specs.Implementation.Services
{
    [Export(typeof(IPostService))]
    internal class PostService : IPostService
    {
        private readonly ISecurityDataModel model;
        private ValidationService<Post> validationService;

        [ImportingConstructor]
        public PostService(ISecurityDataModel model)
        {
            this.model = model;
            InitializeValidationService();
        }

        public Post New()
        {
            return new Post();
        }

        public ErrorCollection Validate(Post post)
        {
            return validationService.GetErrors(post);
        }

        public string[] IsPostUsedAnywhere(Post post)
        {
            var tables = new List<string>();
            if (model.Employees.Any(p => p.ID == post.ID))
                tables.Add(Tables.Employees);

            return tables.ToArray();
        }

        private void InitializeValidationService()
        {
            validationService = new ValidationService<Post>();
            validationService.AddRule(p => p.ID.IsEmpty(), StandardErrorReports.IdPropertyNotSet);
            validationService.AddRule(p => string.IsNullOrWhiteSpace(p.Name), StandardErrorReports.NamePropertyNotSet);
            validationService.AddRule(p => model.Posts.Any(post => post.ID != p.ID && post.Name == p.Name), PostWithSameNameAlreadyExists);
        }

        private ErrorReport PostWithSameNameAlreadyExists(Post post)
        {
            return ErrorReport.Create().
                    InObject(post).
                    WithMessage(Strings.PostWithSameNameAlreadyExists(post)).
                    Severity(ErrorSeverity.Warning);
        }
    }
}